import { TransformNode } from '@babylonjs/core/Meshes/transformNode';
import { DefaultStage } from '../default-stage';
import { ParticleSystem } from '@babylonjs/core/Particles/particleSystem';
import { RawAssetsUrl } from '../../raw-asset-info';
import { MeshBuilder } from '@babylonjs/core/Meshes/meshBuilder';
import { Vector3 } from '@babylonjs/core/Maths/math.vector';
import { Utils } from 'babylon-lib/index';
import { LandscapeManager } from '../landscape/landscape-manager';
import { Color4 } from '@babylonjs/core/Maths/math.color';
import { Helper } from 'babylon-lib/tool/helper';


interface IBattleFieldOptions {
    offset: Vector3
}

/**
 * 战场标识
 */
class BattleField {

    private _stage: DefaultStage;
    private _options: IBattleFieldOptions;
    private _psSmoke: ParticleSystem;

    public readonly id = Utils.id;
    public container: TransformNode;

    constructor(options: IBattleFieldOptions, stage: DefaultStage) {
        this._options = options;
        this._stage = stage;
        this.container = new TransformNode('battleFieldContainer', this._stage.mainScene);
        this._psSmoke = this.initializeSmoke();
    }

    public dispose(): void {
        Helper.getChildMeshes(this.container).forEach(m => {
            if (m.material) m.material.dispose();
            m.dispose();
        });
        this._psSmoke.dispose();
        this.container.dispose();
    }

    private initializeSmoke(): ParticleSystem {
        const texture = this._stage.loader(this._stage.mainScene).getTextureTaskInfo(RawAssetsUrl.textureSmoke)?.texture!;
        const m = MeshBuilder.CreateBox(this.id + 'Emitter', { size: 0.1 }, this._stage.mainScene);
        m.parent = this.container;
        m.position.set(0, 0, 0);

        const ps = new ParticleSystem(this.id + 'Particle', 40, this._stage.mainScene);
        ps.particleTexture = texture;
        ps.minLifeTime = 4;
        ps.maxLifeTime = 6;
        ps.minEmitPower = 0;
        ps.maxEmitPower = 4;
        ps.minAngularSpeed = -0.1;
        ps.maxAngularSpeed = 0.1;
        ps.emitRate = 30;
        ps.createPointEmitter(Vector3.UpReadOnly, Vector3.UpReadOnly);
        ps.emitter = m;
        ps.gravity = LandscapeManager.wind;

        ps.addColorGradient(0, new Color4(1, 1, 1, 0.5), new Color4(1, 1, 1, 1));
        ps.addColorGradient(0.1, new Color4(1, 1, 1, 0.5), new Color4(1, 1, 1, 1));
        ps.addColorGradient(1, new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0));

        ps.addSizeGradient(0, 1, 2);
        ps.addSizeGradient(0.001, 10, 20);
        ps.addSizeGradient(1, 40, 80);

        ps.blendMode = ParticleSystem.BLENDMODE_ADD;
        return ps;
    }

}


export { BattleField };